package com.zthz.douxing

import com.zthz.douxing.utils.CommandAndLog
import com.zthz.douxing.utils.MessageUtils
import grails.plugin.gson.converters.GSON
import grails.plugin.springsecurity.SpringSecurityUtils

class BaseController {

    def errorMessageServicesService
    def springSecurityService
    private Person person

    protected final String SAVE = "save"
    protected final String DELETE="delete"

    public BaseController() {

    }

    protected getI18NErrorByCode(code){

        return errorMessageServicesService.getErrorMsgByCode(code)
    }



    protected  getI18NErrorByCommand(command){

        return errorMessageServicesService.getErrorMsg(command)
    }

    protected  Person getPerson() {

        Person tempPerson=null

        if (springSecurityService.loggedIn) {

            tempPerson =  Person.get(springSecurityService.principal.id)
        }


        return tempPerson
    }

    protected void setPerson(Person person) {

        this.person = person
    }




    protected doAJAXREQUEST(command, Closure excuteBody) {

        if (!SpringSecurityUtils.isAjax(request)) {
            render(["status": 1, "errMsg": getI18NErrorByCode("ajax.isnot"), "data": []] as GSON)
            return
        }

        if (command.hasErrors()) {
            render MessageUtils.getCommandErrorMsgAsJSON(new CommandAndLog(command: command, log: log,
                    errorMsg: errorMessageServicesService.getErrorMsg(command)))
            return
        }


        render (excuteBody(command));
    }

    protected  excuteAction(instance,String methodName,boolean noMesg){

            try {

                if(instance."$methodName"()){

                    return MessageUtils.getSuccessfullMsgAsJSON()
                }
                else{

                    if(!noMesg)

                        return MessageUtils.getCommandErrorMsgAsJSON(errorMessageServicesService.getErrorMsg(instance))

                    else

                        return MessageUtils.getCommandErrorMsgAsJSON("failed")

                }

            }catch (Exception e){

                log.debug(e.printStackTrace())

                return MessageUtils.getCommandErrorMsgAsJSON("failed")

            }

    }


}